import path from "path";
import fs from "fs";
import sharp from "sharp";
import { screenshotPath, ThumbnailSizeLimit, staticPath, ImgExt } from "../utils/const";
import { operateFile } from "./operateFile";
import { base642String, string2Base64 } from "./base64"
import { MediaPromise } from "../interface/interface"


export async function operateImg() {
    await operateFile(staticPath, ImgExt, operateImgFile);
}

// 处理图片格式
export async function operateImgFile(imgPath: string) {
    let stat = await fs.promises.stat(imgPath);
    let ext = path.extname(imgPath);
    let name = path.basename(imgPath, ext);
    if (name.indexOf("_screenshot") !== -1) {
        return;
    }
    let size = stat.size / 1024 / 1024; // 字节转kb
    if (size > 1) {
        sharpImg(imgPath, name, ext).then((res) => {});
    }
}

/**
 * @description: 得到缩略图
 * @param {string} imgPath 图片地址
 * @param {string} name 名字
 * @param {string} ext 缩略图后缀
 * @return {*}
 * @author: tao wenbo 2419421809@qq.com
 */
export async function sharpImg(imgPath: string, name: string, ext: string): Promise<MediaPromise> {
    let dir = path.dirname(imgPath).replace(path.resolve(__dirname, "../../../"), "");
    dir = path.join(screenshotPath, dir);
    name = string2Base64( name ).replace("/", '_')
    try {
        let res = await fs.promises.mkdir(dir, { recursive: true });
    } catch (error) {
        console.log("创建失败");
    }
    return new Promise((resolve) => {
        sharp(imgPath)
            // 获取像素信息
            .metadata()
            .then((metadata) => {
                let { width, height } = metadata;
                let aspectRatio = width! / height! || 0;
                // 读取原始图片
                sharp(imgPath)
                    // 调整图片大小并生成缩略图
                    .resize(Math.floor(ThumbnailSizeLimit * aspectRatio), ThumbnailSizeLimit)
                    // 输出缩略图
                    .toFile(path.resolve(dir, `${name}${ext}`), (err, info) => {
                        if (err) console.error(err);
                        // console.log(info);
                        resolve({
                            path: path.resolve(dir, `${name}${ext}`),
                            duration: 0
                        })
                    });
            })
            .catch((err) => {
                console.error(err);
            });
    });
}
